unit Bubble1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Timer1: TTimer;
    Image1: TImage;
    ScrollBar1: TScrollBar;
    N: TEdit;
    procedure ScrollBar1Change(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  a:boolean;
  run, step : integer;
  mass : array [0..100] of integer;
Const
  W:=10;
  H:=10;
  x:=50;
  y:=50;

implementation

{$R *.dfm}

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  Timer1.Interval:=ScrollBar1.Position*100;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  N:=StrToInt(Edit1.Text);
  Timer1.Enabled:=True;
  step:=0;
  run:=0;
  for i :=0 to N-1 do
    mass[i]:=random(N+50);

end;

procedure TForm1.Start;
var i : integer;
begin
  for i := 0 to N-1 do
  begin
    Form1.Canvas.Brush.Color:=clWhite;
    Form1.Canvas.Pen.Color:=clWhite;
    Form1.Canvas.Rectangle(x+W*i, y, x+W*(i+1), y+h*(N+50));

    Form1.Canvas.Brush.Color:=clAqua;
    Form1.Canvas.Pen.Color:=clBlue;
    Form1.Canvas.Rectangle(x+W*i, y, x+W*(i+1), y+h*mass[i]);
    Form1.Canvas.Rectangle(x+W*(i+1), y, x+W*(i+2), y+h*mass[i+1]);

    if (i=step) and (i+1=step+1) then
    begin
      Form1.Canvas.Brush.Color:=clWhite;
      Form1.Canvas.Pen.Color:=clWhite;
      Form1.Canvas.Rectangle(x+W*i, y, x+W*(i+1), y+h*mass[i]);
      Form1.Canvas.Rectangle(x+W*(i+1), y, x+W*(i+2), y+h*mass[i+1]);

      Form1.Canvas.Brush.Color:=clOrenge;
      Form1.Canvas.Pen.Color:=clRed;
      Form1.Canvas.Rectangle(x+W*i, y, x+W*(i+1), y+h*mass[i]);
      Form1.Canvas.Rectangle(x+W*(i+1), y, x+W*(i+2), y+h*mass[i+1]);
    end;

    if (i+1=step+1) and (i+2=step+2) then
    begin
      Form1.Canvas.Brush.Color:=clWhite;
      Form1.Canvas.Pen.Color:=clWhite;
      Form1.Canvas.Rectangle(x+W*(i+1), y, x+W*(i+2), y+h*mass[i]);
      Form1.Canvas.Rectangle(x+W*(i+2), y, x+W*(i+3), y+h*mass[i+1]);

      Form1.Canvas.Brush.Color:=clOrenge;
      Form1.Canvas.Pen.Color:=clRed;
      Form1.Canvas.Rectangle(x+W*(i+1), y, x+W*(i+2), y+h*mass[i]);
      Form1.Canvas.Rectangle(x+W*(i+2), y, x+W*(i+3), y+h*mass[i+1]);
    end;


  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  for i := 0 to N-1 do
  begin

    if (step=0) then
    a:=true;

    if(mass[i]>mass[i+1]) then
    begin
      mass[i]:=mass[i]+mass[i+1];
      mass[i+1]:=mass[i]-mass[i+1];
      mass[i]:=mass[i]-mass[i+1];
      a:=false;
    end;

    if(step=N-(run+1)) then
      step:=0;
    if (a) or (run=N-1) then
      Timer1.Enabled:=False;
  end;
end;

end.
